<?php

namespace App\Service;

use App\Model\UserAuthModel;
use App\Model\UserModel;
use App\Model\UtilSmsModel;
use App\Utility\JwtManager;
use EasySwoole\Mysqli\Exception\Exception;
use Throwable;

class AuthService extends BaseService
{
    /**
     * 检测是否实名认证
     * @param $uid
     * @return bool
     * @throws Exception
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws Throwable
     */
    public function checkAuth($uid): bool
    {
        $auth = UserAuthModel::create()->getAuth(['uid' => $uid]);
        if (!$auth) {
            return true;
        }

        return true;
    }

    /**
     * @param $uid
     * @param $phone
     * @param $code
     * @param $requestId
     * @param $ip
     * @return array
     * @throws Exception
     * @throws Throwable
     * @throws \EasySwoole\ORM\Exception\Exception
     */
    public function bindPhone($uid, $phone, $code, $requestId, $ip): array
    {
        $sms = UtilSmsModel::create()->getEmail(['requestId' => $requestId]);
        if (!$sms) {
            return [
                'result' => false,
                'msg' => '验证失败'
            ];
        }
        if ($sms->code !== $code * 1) {
            return [
                'result' => false,
                'msg' => '验证码输入错误'
            ];
        }
        if ((time() - $sms->create_time) > 300) {
            return [
                'result' => false,
                'msg' => '当前任务已超时，请重新验证'
            ];
        }

        $model = new UserModel();
        $userCheck = $model->where(['phone' => $phone, 'id' => $uid])->get();

        if (!$userCheck) {
            $userInfo = $model->where(['phone' => $phone])->get();

            $userW = $model->where(['id' => $uid])->get();

            $data['we_code'] = $userW->we_code;
            $data['avatar'] = $userW->avatar;
            $data['username'] = $userW->username;
            if ($userInfo) {
                $res = UserModel::create()->update($data, ['id' => $userInfo->id]);
                $res1 = UserModel::create()->update(['is_deleted' => 1], ['id' => $uid]);
                $uid = $userInfo->id;
            } else {
                $res = UserModel::create()->update(['phone' => $phone], ['id' => $uid]);
            }
            if (!$res) {
                return [
                    'result' => false,
                    'msg' => '手机号绑定失败'
                ];
            }
        }

        $par = [
            'uid' => $uid,
            'phone' => $phone,
            'result' => 1
        ];

        UserService::getInstance()->bindHouse($uid, $phone);
        $r1 = UserAuthModel::create()->addUser($par);
        if (!$r1) {
            return [
                'result' => false,
                'msg' => '手机号绑定失败'
            ];
        }
        $user = $model->where(['id' => $uid])->get();
        return LoginService::getInstance()->loginResult($user, $ip);
    }
}